use slint::{ModelRc, VecModel, SharedString};
use std::{cell::RefCell, rc::Rc, sync::Mutex, time::Duration};
use uuid::Uuid;
use chrono::{DateTime, Local};
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
use std::fs;
use once_cell::sync::Lazy;

mod note_operations;
mod config_manager;

use note_operations::NoteOperations;
use config_manager::ConfigManager;

slint::include_modules!();

#[derive(Debug, Clone, Serialize, Deserialize)]
struct Note {
    id: String,
    title: String,
    content: String,
    color: String,
    created_at: DateTime<Local>,
    updated_at: DateTime<Local>,
    position_x: f32,
    position_y: f32,
    width: f32,
    height: f32,
    is_minimized: bool,
}

impl Note {
    fn new(title: String, color: String, position_x: f32, position_y: f32) -> Self {
        let now = Local::now();
        Self {
            id: Uuid::new_v4().to_string(),
            title,
            content: String::new(),
            color,
            created_at: now,
            updated_at: now,
            position_x,
            position_y,
            width: 200.0,
            height: 200.0,
            is_minimized: false,
        }
    }
    
    // 转换为UI可用的类型
    fn to_slint_note(&self) -> slint::SharedString {
        // 转换成JSON字符串以便在Slint UI中使用
        serde_json::to_string(self).unwrap().into()
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct AppConfig {
    default_color: String,
    font_size: i32,
    opacity: i32,
    auto_start: bool,
    auto_save_interval: i32,
}

impl Default for AppConfig {
    fn default() -> Self {
        Self {
            default_color: "yellow".to_string(),
            font_size: 14,
            opacity: 100,
            auto_start: true,
            auto_save_interval: 30,
        }
    }
}

struct AppData {
    notes: Vec<Note>,
    config: AppConfig,
}

impl AppData {
    fn new() -> Self {
        Self {
            notes: Vec::new(),
            config: AppConfig::default(),
        }
    }

    fn load() -> Self {
        let data_dir = get_app_data_dir();
        let notes_file = data_dir.join("notes.json");
        let config_file = data_dir.join("config.json");

        let notes = if notes_file.exists() {
            match fs::read_to_string(&notes_file) {
                Ok(data) => match serde_json::from_str(&data) {
                    Ok(notes) => notes,
                    Err(e) => {
                        eprintln!("Failed to parse notes data: {}", e);
                        Vec::new()
                    }
                },
                Err(e) => {
                    eprintln!("Failed to read notes file: {}", e);
                    Vec::new()
                }
            }
        } else {
            Vec::new()
        };

        let config = if config_file.exists() {
            match fs::read_to_string(&config_file) {
                Ok(data) => match serde_json::from_str(&data) {
                    Ok(config) => config,
                    Err(e) => {
                        eprintln!("Failed to parse config data: {}", e);
                        AppConfig::default()
                    }
                },
                Err(e) => {
                    eprintln!("Failed to read config file: {}", e);
                    AppConfig::default()
                }
            }
        } else {
            AppConfig::default()
        };

        Self { notes, config }
    }

    fn save(&self) {
        let data_dir = get_app_data_dir();
        fs::create_dir_all(&data_dir).expect("Failed to create app data directory");

        let notes_file = data_dir.join("notes.json");
        let config_file = data_dir.join("config.json");

        match serde_json::to_string_pretty(&self.notes) {
            Ok(data) => {
                if let Err(e) = fs::write(&notes_file, data) {
                    eprintln!("Failed to save notes: {}", e);
                }
            }
            Err(e) => eprintln!("Failed to serialize notes: {}", e),
        }

        match serde_json::to_string_pretty(&self.config) {
            Ok(data) => {
                if let Err(e) = fs::write(&config_file, data) {
                    eprintln!("Failed to save config: {}", e);
                }
            }
            Err(e) => eprintln!("Failed to serialize config: {}", e),
        }
    }
}

fn get_app_data_dir() -> PathBuf {
    let mut dir = dirs::data_dir().expect("Failed to get data directory");
    dir.push("memory_note");
    dir
}

static APP_DATA: Lazy<Mutex<AppData>> = Lazy::new(|| Mutex::new(AppData::load()));

// 将便签列表转换为Slint模型
fn get_notes_model() -> ModelRc<SharedString> {
    let notes = NoteOperations::get_all_notes();
    let model = VecModel::default();
    
    for note in notes {
        model.push(note.to_slint_note());
    }
    
    ModelRc::new(model)
}

// 搜索便签并返回结果模型
fn search_notes_model(query: &str) -> ModelRc<SharedString> {
    let notes = NoteOperations::search_notes(query);
    let model = VecModel::default();
    
    for note in notes {
        model.push(note.to_slint_note());
    }
    
    ModelRc::new(model)
}

fn main() -> Result<(), slint::PlatformError> {
    // 创建主窗口
    let main_window = MainWindow::new()?;
    
    // 示例数据 - 在真实应用中应该从持久化存储加载
    let app_data = APP_DATA.lock().unwrap();
    
    if app_data.notes.is_empty() {
        // 如果没有保存的便签，创建一些示例便签
        drop(app_data);
        let mut app_data = APP_DATA.lock().unwrap();
        
        let note1 = Note::new(
            "工作任务".to_string(),
            "yellow".to_string(),
            50.0,
            50.0,
        );
        
        let mut note1 = note1;
        note1.content = "1. 完成项目报告\n2. 回复邮件\n3. 准备会议材料".to_string();
        
        let note2 = Note::new(
            "购物清单".to_string(),
            "green".to_string(),
            270.0,
            70.0,
        );
        
        let mut note2 = note2;
        note2.content = "- 牛奶\n- 面包\n- 鸡蛋\n- 水果".to_string();
        
        let note3 = Note::new(
            "想法收集".to_string(),
            "blue".to_string(),
            120.0,
            270.0,
        );
        
        let mut note3 = note3;
        note3.content = "旅行计划：计划下个月去杭州旅行，需要提前预订酒店和机票".to_string();
        
        app_data.notes.push(note1);
        app_data.notes.push(note2);
        app_data.notes.push(note3);
        app_data.save();
    }
    
    // 设置便签列表模型
    let notes_model = get_notes_model();
    
    // 处理创建新便签
    let main_window_weak = main_window.as_weak();
    main_window.on_create_new_note(move || {
        let window = main_window_weak.unwrap();
        
        let mut app_data = APP_DATA.lock().unwrap();
        let config = &app_data.config;
        
        // 创建新便签
        let new_note = Note::new(
            "新建便签".to_string(),
            config.default_color.clone(),
            100.0, 
            100.0,
        );
        
        app_data.notes.push(new_note);
        app_data.save();
        
        // 更新UI显示的便签列表
        drop(app_data);
        let notes_model = get_notes_model();
        window.set_notes(notes_model);
    });
    
    // 处理选择便签
    let main_window_weak = main_window.as_weak();
    main_window.on_select_note(move |note_id: SharedString| {
        let note_id = note_id.to_string();
        let app_data = APP_DATA.lock().unwrap();
        
        if let Some(note) = app_data.notes.iter().find(|n| n.id == note_id) {
            println!("选中便签: {}", note.title);
        }
    });
    
    // 处理移动便签
    let main_window_weak = main_window.as_weak();
    main_window.on_move_note(move |note_id: SharedString, x: f32, y: f32| {
        let note_id = note_id.to_string();
        NoteOperations::move_note(&note_id, x, y);
        
        // 更新UI
        let window = main_window_weak.unwrap();
        let notes_model = get_notes_model();
        window.set_notes(notes_model);
    });
    
    // 处理调整便签大小
    let main_window_weak = main_window.as_weak();
    main_window.on_resize_note(move |note_id: SharedString, width: f32, height: f32| {
        let note_id = note_id.to_string();
        NoteOperations::resize_note(&note_id, width, height);
        
        // 更新UI
        let window = main_window_weak.unwrap();
        let notes_model = get_notes_model();
        window.set_notes(notes_model);
    });
    
    // 处理更新便签内容
    let main_window_weak = main_window.as_weak();
    main_window.on_update_note_content(move |note_id: SharedString, content: SharedString| {
        let note_id = note_id.to_string();
        let content = content.to_string();
        NoteOperations::update_note_content(&note_id, content);
        
        // 更新UI
        let window = main_window_weak.unwrap();
        let notes_model = get_notes_model();
        window.set_notes(notes_model);
    });
    
    // 处理更新便签标题
    let main_window_weak = main_window.as_weak();
    main_window.on_update_note_title(move |note_id: SharedString, title: SharedString| {
        let note_id = note_id.to_string();
        let title = title.to_string();
        NoteOperations::update_note_title(&note_id, title);
        
        // 更新UI
        let window = main_window_weak.unwrap();
        let notes_model = get_notes_model();
        window.set_notes(notes_model);
    });
    
    // 处理更改便签颜色
    let main_window_weak = main_window.as_weak();
    main_window.on_change_note_color(move |note_id: SharedString, color: SharedString| {
        let note_id = note_id.to_string();
        let color = color.to_string();
        NoteOperations::change_note_color(&note_id, color);
        
        // 更新UI
        let window = main_window_weak.unwrap();
        let notes_model = get_notes_model();
        window.set_notes(notes_model);
    });
    
    // 处理最小化/恢复便签
    let main_window_weak = main_window.as_weak();
    main_window.on_toggle_minimize_note(move |note_id: SharedString| {
        let note_id = note_id.to_string();
        NoteOperations::toggle_minimize_note(&note_id);
        
        // 更新UI
        let window = main_window_weak.unwrap();
        let notes_model = get_notes_model();
        window.set_notes(notes_model);
    });
    
    // 处理删除便签
    let main_window_weak = main_window.as_weak();
    main_window.on_delete_note(move |note_id: SharedString| {
        let note_id = note_id.to_string();
        NoteOperations::delete_note(&note_id);
        
        // 更新UI
        let window = main_window_weak.unwrap();
        let notes_model = get_notes_model();
        window.set_notes(notes_model);
    });
    
    // 处理搜索便签
    let main_window_weak = main_window.as_weak();
    main_window.on_search_notes(move |query: SharedString| -> ModelRc<SharedString> {
        let query = query.to_string();
        
        if query.is_empty() {
            return get_notes_model();
        }
        
        let search_model = search_notes_model(&query);
        
        // 刷新UI
        let window = main_window_weak.unwrap();
        window.set_notes(search_model.clone());
        
        search_model
    });
    
    // 将初始便签列表传递给UI
    main_window.set_notes(notes_model);
    
    // 设置定时自动保存
    let config = ConfigManager::get_config();
    let auto_save_interval = config.auto_save_interval;
    
    // 使用后台线程实现自动保存
    std::thread::spawn(move || {
        loop {
            std::thread::sleep(Duration::from_secs(auto_save_interval as u64));
            
            let app_data = APP_DATA.lock().unwrap();
            app_data.save();
        }
    });
    
    // 运行应用
    main_window.run()
}
